# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
import enhancedModel as em
import models.manifest as mm

class SOModel( em.EnhancedModel ):
    __prefix__ = 'ShippingOrder'
    
    sender = db.IntegerProperty() 
    recipient = db.IntegerProperty()
    supervisor = db.IntegerProperty(required=True)
    
    origin = db.StringProperty(required=True)	
    originPosition = db.GeoPtProperty()
    
    destination = db.StringProperty(required=True)
    destinationPosition = db.GeoPtProperty()

    
    # id of milestone plan
    mp = db.IntegerProperty()
    startTime = db.DateTimeProperty(required = True)
    
    #set to true if mpChecker does not need to check it again, eg. when order was already checked for delays since last tracking info, and the expected time for current checkpoint on milestone plan has already passed. reset to False after adding each new tracking info for this order
    alreadyChecked = db.BooleanProperty(required = True, default = False) 
    
    finished = db.BooleanProperty(required = True, default=False)
    

    def editLink(self):
        return ("/so/edit/id/%d" % self.ident)

    def deleteLink(self):
        return ("/so/delete/id/%d" % self.ident)

    def showLink(self):
        return ("/so/show1/id/%d" % self.ident)

    def showAllLink(self):
        return "/so/showAll"

    def newLink(self):
        return "/so/new"

    def showTIsLink(self):
        return ("/ti/showAll/SOid/%d" % self.ident)
    
    def manifestsLinks(self):
        links = []
        for m in self.getManifests():
            links.append(m.linkTo(text = str(m.ident)))
        return ", ".join(links) + (" <a href=\"/manifest/new?orders=%d\">[Add]</a>"%self.ident)
            
        
    def getManifests(self):
        return em.EnhancedModel.queryLatest(mm.ManifestModel).filter('orders =', self.ident).fetch(1000)
    
    
        
    @staticmethod
    def decodeTime(timeString):
        splitted = map(int,timeString.split("/"))
        return datetime.datetime(splitted[0], splitted[1], splitted[2], splitted[3])
    
    @staticmethod
    def encodeTime(time):
        return time.strftime("%Y/%m/%d/%H")